﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Signup : System.Web.UI.Page
{
    private string error_msg;
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }
    protected void submit_Click(object sender, EventArgs e)
    {
        //预处理所输入的信息
        string username_worked = username.Text.Trim();

        byte[] password_worked = SHA1.Create().ComputeHash(Encoding.Unicode.GetBytes(password.Text.Trim()));

        string emailAddress_worked = email.Text.Trim();
        Regex emailAddressChecker = new Regex(@"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$", RegexOptions.IgnoreCase);

        string cellphone_worked = cellphone.Text.Trim();
        Regex cellphoneChecker = new Regex(@"^1[3|4|5|8][0-9]\d{8}$");

        string QQ_worked = QQ.Text.Trim();
        Regex QQChecker = new Regex(@"^[1-9]\d{4,10}$");

        //检测必填项有效性
        if (username_worked == string.Empty)
        {
            error_msg = "用户名不能为空，请输入用户名 FROM SERVER";
            notification.InnerHtml = error_msg;
            return;
        }
        else if (password.Text.Trim() == string.Empty)
        {
            error_msg = "密码不能为空，请设置密码 FROM SERVER";
            notification.InnerHtml = error_msg;
            return;
        }
        else if (password_confirm.Text.Trim() == string.Empty)
        {
            error_msg = "请在确认密码输入框中重复输入您的密码 FROM SERVER";
            notification.InnerHtml = error_msg;
            return;
        }
        else if (password.Text != password_confirm.Text)
        {
            error_msg = "两次密码不同，请检查后重新输入 FROM SERVER";
            notification.InnerHtml = error_msg;
            return;
        }
        else if (emailAddress_worked != string.Empty && !emailAddressChecker.IsMatch(emailAddress_worked))
        {
            error_msg = "您输入的电子邮箱地址不合法，请重新输入 FROM SERVER";
            notification.InnerHtml = error_msg;
            return;
        }
        else if (cellphone_worked != string.Empty && !cellphoneChecker.IsMatch(cellphone_worked))
        {
            error_msg = "您输入的手机号码不合法，请重新输入 FROM SERVER";
            notification.InnerHtml = error_msg;
            return;
        }
        else if (QQ_worked != string.Empty && !QQChecker.IsMatch(QQ_worked))
        {
            error_msg = "您输入的QQ号码不合法，请重新输入 FROM SERVER";
            notification.InnerHtml = error_msg;
            return;
        }
        else
        {

            //开始操作数据库，包括检查用户名是否重复、执行注册等
            ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["connectionString"];
            using (SqlConnection dataBaseConnection = new SqlConnection(settings.ConnectionString))
            {
                SqlCommand command = new SqlCommand();
                command.Connection = dataBaseConnection;

                SqlParameter usernameSqlParameter = new SqlParameter("@username", username_worked);
                SqlParameter passwordSqlParameter = new SqlParameter("@password", password_worked);
                SqlParameter emailAddressSqlParameter = new SqlParameter("@emailAddress", emailAddress_worked);
                SqlParameter cellphoneSqlParameter = new SqlParameter("@cellphone", cellphone_worked);
                SqlParameter QQSqlParameter = new SqlParameter("@QQ", QQ_worked);

                //检查该用户名是否已经存在
                string queryString = "SELECT * " +
                                     "FROM users " +
                                     "WHERE username = @username";
                command.CommandText = queryString;
                command.Parameters.Add(usernameSqlParameter);
                dataBaseConnection.Open();
                SqlDataReader reader;
                try
                {
                    reader = command.ExecuteReader();
                }
                catch (Exception)
                {
                    error_msg = "数据库方面发生了错误，请点击页脚的“联系我们”告知我们，我们会尽快修复";
                    notification.InnerHtml = error_msg;
                    return;
                }
                if (reader.HasRows)
                {
                    error_msg = "您想要注册的用户名已经被他人使用<br>请更换用户名之后重试";
                    notification.InnerHtml = error_msg;
                    dataBaseConnection.Close();
                    return;
                }
                reader.Close();

                //通过检查，执行注册
                queryString = "INSERT INTO users(username, password, email, cellphone, QQ) " +
                              "VALUES(@username, @password, @emailAddress, @cellphone, @QQ)";
                command.CommandText = queryString;
                command.Parameters.AddRange(new SqlParameter[]{passwordSqlParameter, emailAddressSqlParameter, cellphoneSqlParameter, QQSqlParameter});
                try
                {
                    command.ExecuteNonQuery();
                }
                catch (Exception exception)
                {
                    error_msg = "数据库方面发生了错误，请点击页脚的“联系我们”告知我们，我们会尽快修复" + exception.Message;
                    notification.InnerHtml = error_msg;
                    return;
                }

                reader.Close();
                dataBaseConnection.Close();
            }
            
            //执行至此已经注册成功，返回成功信息
            error_msg = "<p>欢迎您加入We Easy Project！<br>去<a href=\"login.aspx\">登录</a></p><br><br><p>我们建议您现在就去完善密保信息，否则您不能使用密码找回功能<br><a href=\"passwordProtection.aspx\">去完善密保信息</a></p>";
            form_container.Visible = false;
            aboveOfSignDiv.Visible = false;
            notification.InnerHtml = error_msg;
            return;
        }
    }
}